﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Globalization;
using System.Threading;

namespace Statistic
{
    public class StatsAnalyzer
    {
        private IList<int> keys_ = new List<int>();
        private IList<string> keywords_ = new List<string>();
        private string date_;

        public StatsAnalyzer(IList<string> keywords, string date)
        {
            keywords_ = keywords;
            date_ = date;
        }

        /**
        * Reads the xml file
        * @param path
        *   location of the xml file
        */
        public void ReadXml(string path)
        {
            InitializeVector();
            Thread.CurrentThread.CurrentCulture = new CultureInfo("el-GR", true);
            DateTime dateTime = DateTime.Parse(date_);

            XmlDocument doc = new XmlDocument();
            doc.Load(path);

            XmlNodeList advertisementList = doc.GetElementsByTagName("Advertisement");

            foreach (XmlNode node in advertisementList)
            {
                XmlElement advertiseElement = (XmlElement)node;
                string xmlDate = advertiseElement.GetElementsByTagName("Date")[0].InnerText;

                DateTime dating = DateTime.Parse(xmlDate);
                if (dateTime <= dating)
                {
                    string xmlAdvertisementLink = advertiseElement.GetElementsByTagName("AdvertisementLink")[0].InnerText;
                    CheckKeyWords(xmlAdvertisementLink);
                }
            }
            TextWriter tw = new StreamWriter("yeah.txt");
            for (int i = 0; i < keywords_.Count; i++)
            {
                tw.WriteLine(keywords_[i] + " " + keys_[i]);
            }
            tw.Close();           
        }

        /**
        * Search advertisement text for keywords
        * @param source
        *  advertisement text
        */
        private void CheckKeyWords(string advText)
        {
            CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo;
            for (int i = 0; i < keywords_.Count; i++)
            {
                int positionOfMysql = Compare.IndexOf(advText, keywords_[i].ToString(), CompareOptions.IgnoreCase);
                if (positionOfMysql != -1)
                {
                    keys_[i] = keys_[i] + 1;
                }
            }
        }

        /**
        * Inisialize the vector
        */
        void InitializeVector()
        { 
            for (int i = 0; i < keywords_.Count; i++) 
            {
                keys_.Add(0);
            }
        }
    }
}
